/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.agenda.client.view;

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import com.agenda.PrincipalCliente;
import com.agenda.client.ClienteServidor;
import com.agenda.client.SalaChatLadoCliente;
import com.agenda.client.requisicoes.RequisitarEmoticonRequisicao;
import com.agenda.model.RespostaRequisicao;
import com.agenda.model.Usuario;

/**
 *
 * @author Murilo
 */
public class ChatView extends javax.swing.JFrame {

	/**
	 * Creates new form ChatView
	 */
	public ChatView() {
		initComponents();
		videoButton.setEnabled(false);
	}

	/**
	 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The content of
	 * this method is always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jPanel1 = new javax.swing.JPanel();
		emoticonButton = new javax.swing.JButton();
		jScrollPane2 = new javax.swing.JScrollPane();
		mensagemText = new javax.swing.JTextArea();
		enviarButton = new javax.swing.JButton();
		videoButton = new javax.swing.JButton();
		arquivoButton = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		panelText = new javax.swing.JTextPane();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

		emoticonButton.setText(":-)");
		emoticonButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				emoticonButtonActionPerformed(evt);
			}
		});
		jPanel1.add(emoticonButton);

		jScrollPane2.setPreferredSize(new java.awt.Dimension(300, 113));

		mensagemText.setColumns(20);
		mensagemText.setRows(5);
		mensagemText.setPreferredSize(new java.awt.Dimension(300, 94));
		jScrollPane2.setViewportView(mensagemText);

		jPanel1.add(jScrollPane2);

		enviarButton.setText("Enviar");
		enviarButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				enviarButtonActionPerformed(evt);
			}
		});
		jPanel1.add(enviarButton);

		videoButton.setText("Video");
		videoButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				videoButtonActionPerformed(evt);
			}
		});
		jPanel1.add(videoButton);

		arquivoButton.setText("Arquivo");
		arquivoButton.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				arquivoButtonActionPerformed(evt);
			}
		});
		jPanel1.add(arquivoButton);

		getContentPane().add(jPanel1, java.awt.BorderLayout.PAGE_END);

		jScrollPane1.setMinimumSize(new java.awt.Dimension(150, 150));

		panelText.setMinimumSize(new java.awt.Dimension(6, 120));
		jScrollPane1.setViewportView(panelText);

		getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void enviarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_enviarButtonActionPerformed
		enviarMensagem();
	}//GEN-LAST:event_enviarButtonActionPerformed

	private void emoticonButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_emoticonButtonActionPerformed
		abrirEmoticon();
	}//GEN-LAST:event_emoticonButtonActionPerformed

	private void videoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_videoButtonActionPerformed
		videoEvento();
	}//GEN-LAST:event_videoButtonActionPerformed

	private void arquivoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_arquivoButtonActionPerformed
		arquivoEvento();
	}//GEN-LAST:event_arquivoButtonActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		/*
		 * Set the Nimbus look and feel
		 */
		//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. For details see
		 * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(ChatView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		//</editor-fold>

		/*
		 * Create and display the form
		 */
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				new ChatView().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton arquivoButton;
	private javax.swing.JButton emoticonButton;
	private javax.swing.JButton enviarButton;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JTextArea mensagemText;
	private javax.swing.JTextPane panelText;
	private javax.swing.JButton videoButton;
	// End of variables declaration//GEN-END:variables

	private StringBuilder texto = new StringBuilder();
	private SalaChatLadoCliente salaCliente = null;

	public void addMensagem(Usuario usuario, String mensagem) {
		texto.append("<b>").append(usuario.getLoginEmail()).append("</b> -> ");
		texto.append(mensagem);
		texto.append("\n");

		panelText.setText(texto.toString());
	}

	private void enviarMensagem() {
		try {
			salaCliente.enviarMensagemRoot(PrincipalCliente.getUsuarioLogado(), mensagemText.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}

		mensagemText.setText("");
	}

	private void abrirEmoticon() {
		Boolean liberado = Boolean.FALSE;
		try {
			RespostaRequisicao resposta = ClienteServidor.getINSTANCIA().enviarInformacao(
				new RequisitarEmoticonRequisicao(PrincipalCliente.getUsuarioLogado()));

			if (resposta.isErro()) {
				JOptionPane.showMessageDialog(this, resposta.getMsg());
				return;
			}
			liberado = (Boolean) ClienteServidor.getINSTANCIA().lerObjeto();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ClienteServidor.getINSTANCIA().liberarComunicacao();
		}

		if (liberado) {
			CaracteresView charView = new CaracteresView(this, true);
			charView.setVisible(true);
			String charEscolhido = charView.getCharEscolhido();
			if (charEscolhido != null) {

				mensagemText.setText(mensagemText.getText() + charEscolhido);

			}
		} else {
			JOptionPane.showMessageDialog(this, "Os emoticons estão em uso por outro usuario");
		}
	}

	public void setSalaCliente(SalaChatLadoCliente salaCliente) {
		this.salaCliente = salaCliente;
	}

	private void videoEvento() {
		//Colocar para verificar no servidor.
		try {
			salaCliente.iniciarVideo();
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, e.getMessage());
		}
	}

	private void arquivoEvento() {
		JFileChooser chooser = new JFileChooser();
		chooser.setMultiSelectionEnabled(false);
		int abriu = chooser.showOpenDialog(this);
		if (abriu == JFileChooser.APPROVE_OPTION) {
			File arquivo = chooser.getSelectedFile();
			if (arquivo != null) {
				try {
					salaCliente.enviarArquivo(arquivo);
				} catch (Exception e) {
					e.printStackTrace();
					JOptionPane.showMessageDialog(this, e.getMessage());
				}
			}
		}
	}

	public void ativarBotaoVideo() {
		videoButton.setEnabled(true);
	}
}
